package com.anxin.act.listener;



import com.anxin.act.process.dao.ActProcessDao;
import com.anxin.act.process.service.ActProcessService;
import com.anxin.act.utils.ActUtils;
import com.anxin.common.utils.StringUtils;
import com.anxin.common.utils.sys.DeptUtils;
import com.anxin.common.utils.sys.UserUtils;
import com.anxin.sys.system.entity.SysDept;
import com.anxin.sys.system.entity.SysUser;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.javax.el.ExpressionFactory;
import org.activiti.engine.impl.javax.el.ValueExpression;
import org.activiti.engine.impl.juel.ExpressionFactoryImpl;
import org.activiti.engine.impl.juel.SimpleContext;
import org.activiti.engine.impl.persistence.entity.VariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 流转条件判断监听器-刘翔宇
 * @author Administrator
 *
 */
@Configuration
public class ConditionsListener implements ExecutionListener {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	private ActProcessService actProcessService;
	@Autowired
	private ActProcessDao actProcessDao;
	@Autowired
	private HistoryService historyService;


	@Override
	public void notify(DelegateExecution execution) throws Exception {

	}

	/**
	 * 设置上一审批人信息
	 * @param context
	 * @param factory
	 * @param actId
	 */
	private void setLastAssigneeInfo(SimpleContext context,ExpressionFactory factory,String actId){
		String assigneeUserName = ActUtils.getLastAssignee(actId);

		if (StringUtils.isNotBlank(assigneeUserName)){
			SysUser user = UserUtils.getUserByUserName(assigneeUserName);
			if(user != null){
				context.setVariable("act_process_sysqrbm",factory.createValueExpression(user.getDeptId(),user.getDeptId().getClass()));
			}

		}


	}

	/**
	 * 流程条件判断监听器
	 * @param execution
	 * @param value
	 * @return
	 */
	public boolean conditions(DelegateExecution execution,String value,String taskKey){
		ExpressionFactory factory  = new ExpressionFactoryImpl();
		SimpleContext context = new  SimpleContext();
		// 取特定节点的流程变量
		if (StringUtils.isNotBlank(taskKey)){
			List<HistoricTaskInstance> hiTaskList = historyService.createHistoricTaskInstanceQuery().processInstanceId(execution.getProcessInstanceId()).taskDefinitionKey(taskKey).includeTaskLocalVariables().orderByTaskCreateTime().desc().list();
			if (hiTaskList.size() > 0){
				Map<String, Object> taskLocalVariables = hiTaskList.get(0).getTaskLocalVariables();
				for (String key : taskLocalVariables.keySet()) {
					Object val = taskLocalVariables.get(key);
					if (val!=null) {
						context.setVariable(key,factory.createValueExpression(val,val.getClass()));
					}
				}
			}
		}

		ValueExpression valueExpression = factory.createValueExpression(context, "${" + value + "}", boolean.class);
		return (boolean) valueExpression.getValue(context);

	}



	//${conditionsListener.conditions(execution," act_form_reason == '事假'","1","6be3cfa16ac9437ab5cbfe5f5af799b7")}
	public boolean conditions(DelegateExecution execution,String value){
		value = value.replace("&amp;", "&");

		ExpressionFactory factory  = new ExpressionFactoryImpl();
		SimpleContext context = new  SimpleContext();

		// 申请人ID
		String applyUserName = execution.getVariable("applyUserName", String.class);
		// 设置申请人信息
		this.setUserInfo(context,factory,applyUserName,"sqr");
		// 设置上一审批人信息
		this.setLastAssigneeInfo(context,factory,execution.getProcessInstanceId());

		Map<String, String> dataTableAndDataId = ActUtils.getDataTableAndDataId(execution.getProcessInstanceId());
		// 业务表名
		String actDataTable = dataTableAndDataId.get("actDataTable");
		// 业务ID
		String actDataId = dataTableAndDataId.get("actDataId");

		// 查询业务数据
		if (StringUtils.isNotBlank(actDataTable)){
			Map<String, Object> dataMap = actProcessService.selectData(actDataTable, actDataId);
			if (dataMap != null){
				for (String key:dataMap.keySet()) {
					if (dataMap.get(key)!=null) {
						context.setVariable("act_form_"+key,factory.createValueExpression(dataMap.get(key),dataMap.get(key).getClass()));
					}else {
						context.setVariable("act_form_"+key,factory.createValueExpression("","".getClass()));
					}
				}
			}
		}

		//流程属性
		Map<String, VariableInstance> processMap = execution.getVariableInstances();
		for (String key : processMap.keySet()) {
			VariableInstance variableInstance = processMap.get(key);
			if (variableInstance!=null && variableInstance.getValue()!=null) {
				context.setVariable("act_process_"+key,factory.createValueExpression(variableInstance.getValue(),variableInstance.getValue().getClass()));
			}
		}


		// 计算表达式
		ValueExpression valueExpression = factory.createValueExpression(context, "${" + value + "}", boolean.class);

		return (boolean) valueExpression.getValue(context);


	}

	/**
	 * 设置申请人和上一审批人信息
	 * @param context SimpleContext对象
	 * @param factory ExpressionFactory对象
	 * @param userName 用户登录名
	 * @param type 类型
	 */
	public void setUserInfo(SimpleContext context,ExpressionFactory factory , String userName, String type) {
		SysUser sysUser = UserUtils.findByUserNameContainsDelete(userName);
		SysDept sysDept = DeptUtils.get(sysUser.getDeptId());

		// 申请人岗位

		// 部门
		if (sysDept != null){
			context.setVariable("act_process_sqrbm",factory.createValueExpression(sysDept.getId(),sysDept.getId().getClass()));

			// 部门角色
			// 部门负责人

		}

		// 职位
		String userPost = actProcessDao.findPostByUserId(sysUser.getId());
		if (StringUtils.isNotBlank(userPost)) {
			context.setVariable("act_process_sqrzw", factory.createValueExpression(userPost, userPost.getClass()));
		}


		// 部门角色



		// 部门负责人

		// 部门分管领导

		// 部门副总

	}


}
